<?php
namespace zhtfrontend\controllers;

use common\components\extenders\AjaxObject;
use common\components\helpers\Fun;
use common\components\helpers\Tree;
use common\models\datas\Cate;
use common\models\datas\CateAttr;
use zhtfrontend\components\bases\BaseController;
use yii\db\Query;
use yii\web\Response;

/**
 * Class CateattrController
 * #116 分店分类管理
 */

class CateattrController extends BaseController{
    public $str='';

    public $index=0;

    /*分类已有关联的分类显示*/
    public function actionIndex(){
        /*
         * 1. 将分类获取出树形结构
         * 2. 对于已有的关联表中的
         */
        /*这里的category排序或许应该按照关联表的来然后按照分类表的排序*/
        $categorys = Cate::find()->where(['is_delete'=>0])->orderBy(['sort'=>SORT_ASC])->all();
        $cateattrs = CateAttr::find()->where(['site_id'=>Fun::getSiteId()])->indexBy('cat_id')->asArray()->all();
        $menu_array=[];
        $cateattrpc_ids = $this->__getCateattr_catids('pc');
        $cateattrmobile_ids = $this->__getCateattr_catids('mobile');
        foreach ($categorys as $k=>$v){
            $menu_array[$k]['id']=$v->id;
            $menu_array[$k]['pc_is_show_input']=$this->__getInput($v->id,$cateattrpc_ids,'pc_is_show');//in_array($this->__getPermission($v->id),$permissions)判断是否在已有设置的权限中
            $menu_array[$k]['mobile_is_show_input']=$this->__getInput($v->id,$cateattrmobile_ids,'mobile_is_show');
            $menu_array[$k]['parent_id']=$v->parent_id;
            $menu_array[$k]['name']=$v->name;
            //将分类关联表的排序和分类表的排序合在一起，如果关联有就显示关联的排序。无关联则默认还是分类表的排序
            $menu_array[$k]['pc_sort'] = isset($cateattrs[$v->id]['pc_sort'])?$cateattrs[$v->id]['pc_sort']:0;
            $menu_array[$k]['mobile_sort'] = isset($cateattrs[$v->id]['mobile_sort'])?$cateattrs[$v->id]['mobile_sort']:0;
        }

        $data = (new Tree($menu_array))->get_jquery_tree_array();
        $data =  $this->_getTree($data);
        return $this->render('index',['data'=>$data]);
    }

    public function actionShow(){
        $post = \Yii::$app->request->post();
        \Yii::$app->response->format = Response::FORMAT_JSON;
        $ajax_object = new AjaxObject();
        if(empty($post['id']) || empty($post['field']) || !isset($post['show'])){
            $ajax_object->data = 0;
            $ajax_object->content = '系统错误刷新页面重试';
            return $ajax_object;
        }
        $field = $post['field'];
        $CateModel= CateAttr::find()->where(['site_id'=>Fun::getSiteId(),'cat_id'=>$post['id']])->one();
        if($CateModel!=null){
            $CateModel->$field = $post['show'];
        }else{
            $CateModel = new CateAttr();
            $CateModel->site_id = Fun::getSiteId();
            $CateModel->cat_id = $post['id'];
            if($post['field'] == 'pc_is_show'){
                $CateModel->pc_is_show =$post['show'];
                $CateModel->mobile_is_show =0;
            }else{
                $CateModel->pc_is_show =0;
                $CateModel->mobile_is_show =$post['show'];
            }
            $CateModel->pc_sort = 0;
            $CateModel->mobile_sort = 0;
        }
        if($CateModel->save(false)){
            $ajax_object->data = 1;
            $ajax_object->content = 'ok';

        }else{
            $ajax_object->data = 0;
            $ajax_object->content = '系统错误刷新页面重试！';
        }
        return $ajax_object;
    }
    public function actionSort(){
        $post = \Yii::$app->request->post();
        \Yii::$app->response->format = Response::FORMAT_JSON;
        $ajax_object = new AjaxObject();
        if(empty($post['id']) || empty($post['field']) || !isset($post['thisvalue'])){
            $ajax_object->data = 0;
            $ajax_object->content = '系统错误刷新页面重试';
            return $ajax_object;
        }
        $field = $post['field'];
        $sort = (int)$post['thisvalue'];
        $CateModel= CateAttr::find()->where(['site_id'=>Fun::getSiteId(),'cat_id'=>$post['id']])->one();
        if($CateModel!=null){
            $CateModel->$field = $sort;
        }else{
            $CateModel = new CateAttr();
            $CateModel->site_id = Fun::getSiteId();
            $CateModel->cat_id = $post['id'];
            $CateModel->pc_is_show = 0;
            $CateModel->mobile_is_show = 0;
            if($post['field'] == 'pc_sort'){
                $CateModel->pc_sort =$sort;
                $CateModel->mobile_sort =0;
            }else{
                $CateModel->pc_sort =0;
                $CateModel->mobile_sort =$sort;
            }
        }
        if($CateModel->save(false)){
            $ajax_object->data = 1;
            $ajax_object->content = 'ok';
        }else{
            $ajax_object->data = 0;
            $ajax_object->content = '系统错误刷新页面重试！';
        }
        return $ajax_object;
    }

    public function _getTree($data){
        foreach($data as $key=>$val){
            $this->index+=1;
            if($val['tt-parent-id']==null){
                $this->str.="<tr data-tt-id=".$val['id'].">";}else{
                $this->str.="<tr data-tt-id=".$val['tt-parent-id'].'-'.$val['id']." data-tt-parent-id=".$val['tt-parent-id'].">";
            }
            $this->str.="<td>"."$this->index"."</td>";
            if(isset($val['children']) && !empty($val['children'])){
                if($val['parent_id'] > 0 && !empty($val['children'])){
                    $this->str.="<td class='yx-text-left1'><span class='folder zx_mg19'>".$val['name']."</span></td>";
                }else{
                    $this->str.="<td class='yx-text-left1'><span class='folder'>".$val['name']."</span></td>";
                }

            } else{
                $this->str.="<td class='yx-text-left1'><span class='file zx_mg19'>".$val['name']."</span></td>";
            }
           $this->str .='<td>'.$val['pc_is_show_input'].'</td>';
           $this->str .='<td>'.$val['mobile_is_show_input'].'</td>';
           $this->str .='<td class="click" data-field="pc_sort" data-id="'.$val['id'].'">'.$val['pc_sort'].'</td>';
           $this->str .='<td class="click" data-field="mobile_sort" data-id="'.$val['id'].'">'.$val['mobile_sort'].'</td>';

            if(isset($val['children'])&& !empty($val['children'])) $this->_getTree($val['children']);
        }
        return $this->str;
    }

    /*分类显示 更改数据库记录*/
    private function __category_show($categoryid,$service='pc'){
        $cateattr = CateAttr::find()->where(['cat_id'=>$categoryid,'site_id'=>Fun::getSiteId()])->all();
        if($service == 'mobile'){
            $showservice = 'mobile_is_show';
        }else{
            $showservice = 'pc_is_show';
        }
        if(count($cateattr)>0){
            //更新操作
            CateAttr::updateAll([$showservice=>1],['cat_id'=>$categoryid,'site_id'=>Fun::getSiteId()]);
        }else{
            //插入操作
            $cateattr_model = new CateAttr();
            $cateattr_model->site_id = Fun::getSiteId();
            $cateattr_model->cat_id = $categoryid;
            $cateattr_model->$showservice = 1;
            $cateattr_model->save(false);
        }
    }

    /*分类排序 更改数据库记录*/
    private function __category_sort($categoryid,$sort=0,$service='pc'){
        $model=CateAttr::findOne(['cat_id'=>$categoryid,'site_id'=>Fun::getSiteId()]);//获取存在该分类的关联
        if($service == 'mobile'){
            $sortservice = 'mobile_sort';
        }else{
            $sortservice = 'pc_sort';
        }
        if($model){//存在关联，执行更新
            $model->$sortservice = $sort;
            $model->save(false);
        }else{
            //无关联，执行创建操作
            $model = new CateAttr();
            $model->cat_id = $categoryid;
            $model->$sortservice = $sort;
            $model->site_id = Fun::getSiteId();
            $model->save(false);
        }
    }

    /*选择框*/
    private function __getInput($id,$is_check,$service=''){
        $checked = '';
        if(in_array($id,$is_check)){
            $checked = 'checked';
        }
        $str="<input name='ids{$service}[]' class='yx-switch selectAll{$service}' value='{$id}' $checked type='checkbox' data-field='{$service}' class='input-checkbox'>";
        return $str;
    }

    /*分店分类显示的相关表记录操作*/
    private function __getCateattr_catids($service=''){
        $cateattrids = (new Query())->select('cat_id')->from("{{%cate_attr}}")->where(['site_id'=>Fun::getSiteId()]);
        if($service == 'pc'){
            $cateattrids->andWhere(['pc_is_show'=>1]);
        }elseif($service == 'mobile'){
            $cateattrids->andWhere(['mobile_is_show'=>1]);
        }
        $cateattrids = $cateattrids->column();
        if(!empty($cateattrids)){
            return $cateattrids;
        }else{
            return [];
        }
    }

    /*对于有子类的父分类取消显示提示有误的方法*/
    private function _getRemoveParentCatePermission($service='pc',$checked_show_ids){
        if($service == 'mobile'){
            $previous_showcateids = CateAttr::find()->select(['cat_id'])->where(['site_id'=>Fun::getSiteId(),'mobile_is_show'=>1])->asArray()->column();
        }else{
            $previous_showcateids = CateAttr::find()->select(['cat_id'])->where(['site_id'=>Fun::getSiteId(),'pc_is_show'=>1])->asArray()->column();
        }
        $showcat_differ_arr = [];
        foreach($previous_showcateids as $pre_showcatid){
            if(!in_array($pre_showcatid,$checked_show_ids)){
                $showcat_differ_arr[] = $pre_showcatid;//之前显示选择的现在没有选择，要判断是否其子类还选了
            }
        }
        foreach($showcat_differ_arr as $showcate_differ){
            $cate = Cate::findOne($showcate_differ);
            $cate_childids = $cate->arrchild_id;
            $cate_childids_arr = explode(',',$cate_childids);
            foreach($cate_childids_arr as $cate_childid){
                if($cate_childid != $showcate_differ){//子类id不是当前的id
                    if(in_array($cate_childid,$checked_show_ids)){//如果其子类存在于选择显示的分类id中
                        return false;
                    }
                }
            }
        }
        return true;
    }

    //要选择最末梢的具体分类
    /**private function _haveLastCategoryChecked($checked_show_ids){
        foreach($checked_show_ids as $checked_showid){
            $lastresult = false;
            $cate = Cate::findOne($checked_showid);
            if($cate->arrchild_id != (string)$cate->id){//有子分类的
                $cate_child_arr = explode(',',$cate->arrchild_id);
                unset($cate_child_arr[0]);//删除第一个元素，和本id一致的那个元素
                $lastcatechild = [];
                foreach($cate_child_arr as $catechild){
                    $catechild = Cate::findOne($catechild);
                    if($catechild->arrchild_id == (string)$catechild->id){
                        $lastcatechild[] = $catechild->id;//得到了当前选择元素的最终端子类元素id
                    }
                }
                foreach($lastcatechild as $lastcate){
                    if(in_array($lastcate,$checked_show_ids)){
                        $lastresult = true;
                        break;
                    }
                }
                if(!$lastresult){//选择的分类没有当前遍历分类的最末梢分类
                    return $lastresult;
                }
            }
        }
        return true;
    }*/
}